<template>
<div class="login">
    <div>登录名: <input type="text" v-model.trim="username" id="name" name="name"> </div>
    <div>密码: <input type="text" v-model.trim="password" id="pwd" name="pwd"> </div>
    <div>
        <button @click="reset">重置</button>
        <button @click="login">登录</button>
        <button @click="register">注册</button>
    </div>
</div>
</template>
  <script>
  import axios from 'axios';
  export default {
    name: 'MyLogin',
    data() {
        return {
            username:"",
            password:"",
        };
    },
    methods: {
        reset(){
            this.username="";
            this.password="";
        },
        login(){
            axios({
                method: 'post',
                url: 'http://106.52.94.26:3001/user/login',
                data: {
                    username: this.username,
                    password: this.password
                },
            }).then((res) =>{
                console.log(res);
                if(res.data.code===200){
                    //登录成功
                    //1.存储token
                    window.sessionStorage.setItem("token",res.data.token);
                    //2.存储user
                    window.sessionStorage.setItem("user",JSON.stringify(res.data.user));
                    //3.跳转到后台主页
                    this.$router.push("/home");
                }else{
                    alert("登录失败");
                }
            })
        },
        register(){
            axios({
                method: 'post',
                url:'http://106.52.94.26:3001/user/register',
                data: {
                    username: this.username,
                    password: this.password
                }
            }).then((res)=>{
                console.log(res);
                if(res.data.code===200){
                    window.sessionStorage.setItem("token",res.data.token);
                    window.sessionStorage.setItem("user",JSON.stringify(res.data.user));
                }else{
                    alert("注册失败");
                }
            })
            
        }


    }
  }
  </script>

  </style>
  